package com.heima.user.service.impl;

import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserFollowService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ApUserFollowServiceImpl implements ApUserFollowService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //1.todo 校验参数
        if(dto == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.todo 判断是否登录
        ApUser user = ApUserThreadLocalUtil.getUser();
        if(user == null || user.getId() == 0){
            //如果是游客或者没有登录，那么直接结束
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.todo 判断是关注还是取消关注
        if(dto.getOperation() == 0){
            //3.1 todo 关注， 1.给用户添加关注人，2.给作者添加粉丝
            //用户ID  作者ID   并且有一个时间顺序   key + value + 时间 = zset
            //3.1.1 todo  1.给用户添加关注人
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(),dto.getAuthorId()+"",new Date().getTime());
            //3.1.2 todo 2.给作者添加粉丝
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + dto.getAuthorId(), user.getId().toString() ,new Date().getTime());
            return ResponseResult.okResult(AppHttpCodeEnum.FOLLOW_SUCCESS);
        }else{
            //3.2 todo 取消关注 1.给用户删除关注人，2.给作者删除粉丝
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(),dto.getAuthorId()+"");
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + dto.getAuthorId(), user.getId().toString());
            return ResponseResult.okResult(AppHttpCodeEnum.UNFOLLOW_SUCCESS);
        }
    }
}
